package com.flute.haflute.agent.manage;

import java.util.Collection;

import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.haflute.agent.topo.ClusterMessageListener;
import com.flute.haflute.common.ClusterConstants;
import com.flute.haflute.common.ClusterConstants.COMMAND;
import com.flute.haflute.master.Master;
import com.flute.haflute.net.messaging.Message;
import com.flute.haflute.slave.Child;
import com.flute.haflute.tools.ClusterUtils;

/**
 * 监听集群系统消息的处理器 1. 如果接收到集群关闭消息，则关闭本节点
 * 
 */
public class ClusterManagementListener implements ClusterMessageListener {

	private static Logger logger = LoggerFactory
			.getLogger(ClusterManagementListener.class);

	/*
	 * @see com.flute.haflute.agent.topo.ClusterMessageListener#asyncHandle(com
	 * .flute.haflute.net.messaging.Message,
	 * org.apache.mina.core.session.IoSession)
	 */
	@Override
	public void asyncHandle(Message message, IoSession session) {

		if (message.getMessageType().equals(ClusterConstants.SHUTDOWN_CLUSTER)) {

			logger.info("SHUTDOWN message received, agent will shutdown");
			ClusterUtils.exitGracefully();

		} else if (message.getMessageType().equals(
				ClusterConstants.SHUTDOWN_CHILD)) {

			byte[] slaveTag = message.getHeader(ClusterConstants.JOB_SLAVE_TAG);

			if (slaveTag != null) {
				// shutdown slaves
				logger.info("received SHUTDOWN SLAVE message");
				JvmManager jvmManager = JvmManager.getInstance(
						Child.class.getName(), null);
				synchronized (jvmManager) {
					Collection<Process> processes = jvmManager.getAllProcess();
					for (Process process : processes) {
						JvmManager
								.sendCommand2OneJvm(process, COMMAND.SHUTDOWN);
						// process.destroy();
					}
					jvmManager.clearProcessCache();
				}
				logger.info("SHUTDOWN SLAVES ok");
			}

			byte[] masterTag = message
					.getHeader(ClusterConstants.JOB_MASTER_TAG);

			if (masterTag != null) {
				// shutdown master
				logger.info("received SHUTDOWN MASTER message");
				JvmManager jvmManager = JvmManager.getInstance(
						Master.class.getName(), null);
				synchronized (jvmManager) {
					Collection<Process> processes = jvmManager.getAllProcess();
					for (Process process : processes) {
						JvmManager
								.sendCommand2OneJvm(process, COMMAND.SHUTDOWN);
						// process.destroy();
					}
					jvmManager.clearProcessCache();
				}
				logger.info("SHUTDOWN MASTER ok");
			}
		}
	}
}
